package dao

import (
	"app/internal/store/conf"
	"app/internal/struct/store"
	"app/util"
)

func OpenDB(d *Dao, conf *conf.AppConf) error {

	return d.db.Open("mysql", conf.GetMySqlAddr())
}

func CheckTable(dao *Dao) error {

	if err := dao.db.SyncTable(new(store.User)); err != nil {
		util.Error("dao.db.Sync User table %s", err)
		return err
	}

	if err := dao.db.SyncTable(new(store.Heart)); err != nil {
		util.Error("dao.db.Sync Heart table %s", err)
		return err
	}

	if err := dao.db.SyncTable(new(store.Register)); err != nil {
		util.Error("dao.db.Sync Register table %s", err)
		return err
	}

	if err := dao.db.SyncTable(new(store.Policy)); err != nil {
		util.Error("dao.db.Sync Policy table %s", err)
		return err
	}

	if err := dao.db.SyncTable(new(store.License)); err != nil {
		util.Error("dao.db.Sync License table %s", err)
		return err
	}

	return nil
}

func SyncLicenseRecords(dao *Dao) error {

	return dao.db.Select(&store.License{}, func(idx int, bean interface{}) error {
		li := bean.(*store.License)
		dao.StoreBufferLicense(li)
		return nil
	})

}

func (d *Dao) SeleteId(obj interface{}) (v interface{}) {

	var value interface{}

	d.db.Select(obj, func(idx int, bean interface{}) error {
		value = bean
		return nil
	})

	return value
}
